/**
 *
 */
package com.sense.lib.webview.utils

import android.content.Context
import android.graphics.Bitmap
import android.media.MediaScannerConnection
import android.net.Uri
import android.provider.MediaStore
import android.util.Log
import java.io.File
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.io.IOException

object WebFileUtil {
    private val TAG = " WebFileConfig"

    //应用目录
    const val SENSE_DIR = "sense"

    // 图片保存路径
    var IMAGE_PATH = "images"

    // 音频保存路径
    var VOICE_PATH = "voices"

    // 视频保存路径
    var VIDEO_PATH = "videos"

    private fun getPictureDir(context: Context): String {
        return getFileCacheDir(context, IMAGE_PATH)
    }

    fun getVoiceDir(context: Context): String {
        return getFileCacheDir(
            context,
            VOICE_PATH
        )
    }

    fun getVideoDir(context: Context): String {
        return getFileCacheDir(
            context,
            VIDEO_PATH
        )
    }


    /**
     * @Description 创建app 私有文件目录
     * @Author Lionszhang
     * @Date 2021/11/15
     * @param dir 应用私用文件目录包名下第二级目录 path/dir
     * @return  文件夹路径
     */
    private fun getFileCacheDir(context: Context, dir: String): String {
        val appFileDir = File(context.getExternalFilesDir(SENSE_DIR), dir)
        if (!appFileDir.exists()) {
            appFileDir.mkdirs()
        }
        val path = appFileDir.absolutePath
        Log.e(TAG, "path=$path")
        return path
    }


    fun getFileByName(context: Context,fileName: String): File {
        var mediaFile= File(getPictureDir(context), fileName)
        if (!mediaFile.exists()) {
            try {
                mediaFile.createNewFile()
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
        return mediaFile
    }

  private  fun getPictureFile(context: Context): File {
        var mediaFile= File(getPictureDir(context), createFileName())
        if (!mediaFile.exists()) {
            try {
                mediaFile.createNewFile()
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
        return mediaFile
    }
    /**
     * @Description 保存图片到私有目录
     * @Author Lionszhang
     * @Date 2021/11/15
     * @param dir 目录
     * @param fileName 图片名
     * @return  返回保存的文件
     */

    fun saveImage(dir: String, fileName: String, bitmap: Bitmap?): File {
        val imgFileDir = File(dir)
        var os: FileOutputStream? = null
        if (!imgFileDir.exists()) {
            imgFileDir.mkdir()
        }
        val imgFile = File("$dir/$fileName")
        try {
            os = FileOutputStream(imgFile)
        } catch (e: FileNotFoundException) {
            e.printStackTrace()
        }
        bitmap?.compress(Bitmap.CompressFormat.JPEG, 20, os)
        try {
            os?.flush()
            os?.close()
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return imgFile
    }


    /**创建文件*/
  private  fun createFileName(): String {
        return "IMG_"+System.currentTimeMillis().toString() + ".jpg"
    }


    fun saveImageToGallery(context: Context, bmp: Bitmap): Uri? {
        // 首先保存图片
        var imageUri: Uri? = null
        val appDir = getPictureFile(context)
        val fileName = System.currentTimeMillis().toString() + ".jpg"
        val file = File(appDir, fileName)
        try {
            val fos = FileOutputStream(file)
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos)
            fos.flush()
            fos.close()
        } catch (e: FileNotFoundException) {
            e.printStackTrace()
        } catch (e: IOException) {
            e.printStackTrace()
        } catch (e: OutOfMemoryError) {
            try {
                val fos = FileOutputStream(file)
                bmp.compress(Bitmap.CompressFormat.JPEG, 75, fos)
                fos.flush()
                fos.close()
            } catch (e: OutOfMemoryError) {
                System.gc()
                return null
            }
        }
        // 其次把文件插入到系统图库
        try {
            val str = MediaStore.Images.Media.insertImage(
                context.contentResolver,
                file.absolutePath, fileName, null
            )
            imageUri = Uri.parse(str)
        } catch (e: FileNotFoundException) {
            e.printStackTrace()
        }
        // 最后通知图库更新
//        context.sendBroadcast(
//            Intent(
//                Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
//                Uri.parse("file://${R.attr.path}")
//            )
//        )
//        val file = File(imageUri)
        MediaScannerConnection.scanFile(context, arrayOf(file.toString()),
            null, null)
        return imageUri
    }
}